/**
 * @Copyright:Copyright (c) 1992 - 2015
 * @Company: TengTong
 */
package com.tengtong.duang.commons.convert;

import java.util.HashSet;
import java.util.Set;

import com.tengtong.duang.commons.convert.support.ConditionalConverterAdapter;

/**
 * 转换服务类
 *
 * @author jai
 * @since: v1.0
 */
public class ConversionService {

	/**
	 * 没有找到对应的转换器将返回本常量
	 */
	public final static Object NOT_FOUND_CONVERTER = new Object();
	
	/**
	 * 转换器记录集
	 */
	private final Set<ConditionalConverter> converters = new HashSet<>();
	
	/**
	 * 将 数据源转为 类型是 targetType 的数据
	 * 
	 * @param source
	 * @param targetType
	 * @return
	 */
	public <T> T convert(Object source, Class<T> targetType){
		ConditionalConverter converter = null;
		for(ConditionalConverter c: converters){
			if(c.matches(source.getClass(), targetType)){
				converter = c;
				break;
			}
		}
		if(converter != null){
			return (T)converter.convert(source, targetType);
		}
		
		return (T)NOT_FOUND_CONVERTER;
	}
	
	/**
	 * 添加转换器
	 *
	 * @param converter
	 */
	public ConversionService addConverter(ConditionalConverter converter) {
		converters.add(converter);
		
		return this;
	}

	/**
	 * 添加转换器
	 * 
	 * @param converter
	 * @return
	 */
	public ConversionService addConverter(Converter<?, ?> converter){
		converters.add(new ConditionalConverterAdapter(converter));
		
		return this;
	}
	
}
